package com.dayatang.product.webapp.executor;

import javax.mail.MessagingException;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.Email;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;

import com.dayatang.product.domain.EmailInfo;

/**
 * 文件名:MessageTaskExecutor.java
 * 描述:消息邮件异步执行器
 * 创建时间:2012-6-5 下午10:17:47
 * 创建者:mluo
 * 版本号:v2.0
 */
public class MessageTaskExecutor extends BaseTaskExecutor {
	
	private class MessageTask implements Runnable {

		private String companyName;
		private EmailInfo emailInfo;
		
		public MessageTask(String companyName, EmailInfo emailInfo) {
			this.companyName = companyName;
			this.emailInfo = emailInfo;
		}

		public void run() {
			sendMessageEmail(emailInfo,companyName);
		}
		
	}
	
    public void sendMail(String companyName) {
    	taskExecutor.execute(new MessageTask(companyName,EmailInfo.getDefault()));
    }

	private String sendMessageEmail(EmailInfo emailInfo, String companyName) {
		try {
			Email email = new SimpleEmail();
			email.setHostName(emailInfo.getSmtpName());
			email.setSmtpPort(emailInfo.getSmtpPort());
			email.setAuthenticator(new DefaultAuthenticator(emailInfo.getUsername(),emailInfo.getPassword()));
			email.setTLS(false);
			email.setFrom(emailInfo.getUsername());
			email.addTo("547531167@qq.com");
			email.setCharset(CHAREST);
			email.setSubject("客户申请试用通知邮件");
			email.buildMimeMessage();
			email.getMimeMessage().setText("客户:" + companyName + ",申请试用产品,请尽快审批！", CHAREST);
			email.sendMimeMessage();
			return "邮箱测试成功！";
		} catch (EmailException e) {
			return e.toString();
		} catch (MessagingException e) {
			return e.toString();
		} 
	}

}
